package com.xhwl.logistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhwl.common.enums.vehicle.CardTypeEnum;
import com.xhwl.common.enums.vehicle.InOutEnum;
import com.xhwl.common.enums.vehicle.ReleaseTypeEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.device.DeviceProjSupplierCategory;
import com.xhwl.common.pojo.cent.sdata.Project;
import com.xhwl.common.pojo.cent.vehicle.VehcCar;
import com.xhwl.common.pojo.cent.vehicle.VehcCarRecord;
import com.xhwl.common.pojo.cent.vehicle.VehcPassage;
import com.xhwl.common.query.cent.device.ProductAccessQuery;
import com.xhwl.common.query.cent.sdata.ProjectQuery;
import com.xhwl.logistics.dao.VehcCarDao;
import com.xhwl.logistics.dao.VehcCarRecordDao;
import com.xhwl.logistics.dao.VehcParkingLotDao;
import com.xhwl.logistics.dao.VehcPassageDao;
import com.xhwl.logistics.dto.CarInDTO;
import com.xhwl.logistics.dto.CarOutDTO;
import com.xhwl.logistics.service.IDateReportService;
import com.xhwl.logistics.service.cent.IProductAccessCentService;
import com.xhwl.logistics.service.cent.IProjectService;
import com.xhwl.logistics.util.DateFormatUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @description: 车场数据上报
 * @author: lu.Aaron
 * @create: 2021-07-06 15:55
 **/
//@Service
@Slf4j
public class DataReportServiceImpl implements IDateReportService {

    @Autowired
    private IProjectService iProjectService;

    @Autowired
    private VehcCarRecordDao vehcCarRecordDao;

    @Autowired
    private VehcParkingLotDao vehcParkingLotDao;

    @Autowired
    private VehcCarDao vehcCarDao;

    @Autowired
    private VehcPassageDao vehcPassageDao;

    @Autowired
    private IProductAccessCentService productAccessCentService;
    /**
     * 进场数据上报
     * @param carInDTO
     * @return
     */
    @Override
    public ResultJson postCarInInfo(CarInDTO carInDTO) {
        log.info("开始车场车辆进场数据上报：{}",carInDTO.getTrafficId());
        Integer carType = carInDTO.getCarType();
        String entryPlace = carInDTO.getEntryPlace();
        String entryTime = carInDTO.getEntryTime();
        String imgInfo = carInDTO.getImgInfo();
        Integer passType = carInDTO.getPassType();
        @NotNull(message = "车场id必传") Integer parkId = carInDTO.getParkId();
        @NotEmpty(message = "车牌号必填") String plateNo = carInDTO.getPlateNo();
        @NotEmpty(message = "出入场唯一记录ID必填") String trafficId = carInDTO.getTrafficId();
        VehcCarRecord vehcCarRecord = new VehcCarRecord();

        ProductAccessQuery productAccessQuery = new ProductAccessQuery();
        productAccessQuery.setJsonFieldName("thirdParkId");

        //cent-common修改ProductAccessQuery setJsonFieldValue
        productAccessQuery.setJsonFieldValue(parkId);

        List<DeviceProjSupplierCategory> deviceProjSupplierCategories = productAccessCentService.listProductAccess(null, productAccessQuery);
        if (deviceProjSupplierCategories.isEmpty()) {
            throw new BusinessException("请通知系统运维人员，先配置该车场与项目的关联关系");
        }
        if (!deviceProjSupplierCategories.isEmpty()) {
            log.info("获取到的供应商配置结构：{}",deviceProjSupplierCategories.get(0));
            Integer projectId = deviceProjSupplierCategories.get(0).getProjectId();
            ProjectQuery projectQuery = new ProjectQuery();
            projectQuery.withId(projectId);
            log.info("查询主数据项目信息：{}",projectId);
            Project project = iProjectService.getOne(projectQuery, null);
            log.info("查询主数据项目信息：结果{}",project);
            if (!Objects.isNull(project)) {
                vehcCarRecord.setProjectId(projectId);
                vehcCarRecord.setProjectName(project.getName());
                vehcCarRecord.setProjectCode(project.getCode());
                //通过车牌号查询车主
                VehcCar vehcCar = vehcCarDao.selectOne(new QueryWrapper<VehcCar>().eq("plate_number", plateNo).eq("project_id", projectId));
                if (!Objects.isNull(vehcCar)) {
                    vehcCarRecord.setOwnerName(vehcCar.getOwnerName());
                    vehcCarRecord.setOwnerPhone(vehcCar.getOwnerPhone());
                }
            }
        }
        vehcCarRecord.setEnterTime(DateFormatUtil.stringDate2Date(entryTime));
        vehcCarRecord.setEnterPicUrl(imgInfo);
        if (passType==0||passType==1) {

            vehcCarRecord.setEnterType(ReleaseTypeEnum.AUTO);
        }
        if (passType==2) {
            vehcCarRecord.setEnterType(ReleaseTypeEnum.MANUAL);
        }
        if (carType==0) {
            vehcCarRecord.setCardType(CardTypeEnum.TEMPORARILY);
        }else if(carType==2){
            vehcCarRecord.setCardType(CardTypeEnum.MONTH);
        }else if (carType==3){
            vehcCarRecord.setCardType(CardTypeEnum.STORE);
        }
        vehcCarRecord.setThirdParkId(String.valueOf(parkId));
        vehcCarRecord.setPlateNumber(plateNo);
        vehcCarRecord.setStatus(InOutEnum.IN);
        vehcCarRecord.setRecordId(trafficId);
        //入口名称（6.x系统取值是：通道名称 +“- ”+ 通道id；5.x系统取值是：通道名称（后续也需要调整成6.x一样，对接方需要兼容）,通过“-”截取
        List<String> list = Arrays.asList(entryPlace.split("-"));
        String enterPassage = list.get(0);
        String passageId = list.get(1);
        StringBuilder builder = new StringBuilder();
        String thirdPassageId = builder.append(carInDTO.getParkId()).append("-").append(passageId).toString();

        //查询通道信息
        VehcPassage vehcPassage = vehcPassageDao.selectOne(new QueryWrapper<VehcPassage>().eq("third_passage_id", thirdPassageId));
        vehcCarRecord.setEnterPassageId(vehcPassage.getId());
        vehcCarRecord.setEnterPassage(enterPassage);
        vehcCarRecordDao.insert(vehcCarRecord);
        log.info("车场车辆进场数据上报成功");
        return ResultJson.success("车场车辆进场数据上报成功");
    }

    /**
     * 出场数据上报
     * @param carOutDTO
     * @return
     */
    @Override
    public ResultJson postCarOutInfo(CarOutDTO carOutDTO) {
        log.info("开始车场车辆进场数据上报：{}",carOutDTO.getTrafficId());
        Integer carType = carOutDTO.getCarType();
        String leavePlace = carOutDTO.getLeavePlace();
        String leaveTime = carOutDTO.getLeaveTime();
        String imgInfo = carOutDTO.getImgInfo();
        Integer passType = carOutDTO.getPassType();
        @NotNull(message = "车场id必传") Integer parkId = carOutDTO.getParkId();
        @NotEmpty(message = "车牌号必填") String plateNo = carOutDTO.getPlateNo();
        @NotEmpty(message = "出入场唯一记录ID必填") String trafficId = carOutDTO.getTrafficId();
        CarOutDTO.CarExtInfo carExtInfo = carOutDTO.getCarExtInfo();
        ProductAccessQuery productAccessQuery = new ProductAccessQuery();
        productAccessQuery.setJsonFieldName("thirdParkId");

        //cent-common修改ProductAccessQuery setJsonFieldValue
        productAccessQuery.setJsonFieldValue("parkId");

        List<DeviceProjSupplierCategory> deviceProjSupplierCategories = productAccessCentService.listProductAccess(null, productAccessQuery);
        if (!deviceProjSupplierCategories.isEmpty()) {
            Integer projectId = deviceProjSupplierCategories.get(0).getProjectId();
            ProjectQuery projectQuery = new ProjectQuery();
            projectQuery.withId(projectId);
            log.info("查询主数据项目信息：{}",projectId);
            Project project = iProjectService.getOne(projectQuery, null);
            log.info("查询主数据项目信息：结果{}",project);
        }

        VehcCarRecord vehcCarRecord = vehcCarRecordDao.selectOne(new QueryWrapper<VehcCarRecord>().eq("record_id", trafficId));
        if (Objects.isNull(vehcCarRecord)) {
            throw new BusinessException("该出场车无进场记录，请确认是否准确");
        }
        vehcCarRecord.setExistTime(DateFormatUtil.stringDate2Date(leaveTime));
        vehcCarRecord.setExistPicUrl(imgInfo);
        if (passType==0||passType==1) {

            vehcCarRecord.setExistType(ReleaseTypeEnum.AUTO);
        }
        if (passType==2) {
            vehcCarRecord.setExistType(ReleaseTypeEnum.MANUAL);
        }

        vehcCarRecord.setThirdParkId(String.valueOf(parkId));
        vehcCarRecord.setStatus(InOutEnum.OUT);
        //入口名称（6.x系统取值是：通道名称 +“- ”+ 通道id；5.x系统取值是：通道名称（后续也需要调整成6.x一样，对接方需要兼容）,通过“-”截取
        List<String> list = Arrays.asList(leavePlace.split("-"));
        String exitPassage = list.get(0);
        String passageId = list.get(1);
        StringBuilder builder = new StringBuilder();
        String thirdPassageId = builder.append(carOutDTO.getParkId()).append("-").append(passageId).toString();

        //查询通道信息
        VehcPassage vehcPassage = vehcPassageDao.selectOne(new QueryWrapper<VehcPassage>().eq("third_passage_id", thirdPassageId));
        vehcCarRecord.setExistPassageId(vehcPassage.getId());
        vehcCarRecord.setExistPassage(exitPassage);
        vehcCarRecordDao.updateById(vehcCarRecord);
        log.info("车场车辆出场数据上报成功");
        return ResultJson.success("车场车辆出场数据上报成功");
    }
}

